import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

# Import data model classes so that we can use them without module name
from datamodel import *
from rules import *

ruleBase = RuleBase()

class MainPage(webapp.RequestHandler):
  """
  Main page: displays login/logout and shows the main table of things.
  Eventually we might want to have everything in one page and hook up other 'pages'
  via AJAX
  """
  def get(self):
    user = users.get_current_user()
    if user:
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      self.redirect(users.create_login_url(self.request.uri))
      return

    # Dictionary of template parameters
    template_values = {
                       'topLevel' : self.makeAssetTypeTree(user),
                       'docPlaces' : self.getDocumentPlaces(user),
                       'url': url,
                       'url_linktext': url_linktext,
                       'user': user
                       }

    path = os.path.join(os.path.dirname(__file__), 'html', 'mainPage.html')
    self.response.out.write(template.render(path, template_values))
    
  def makeAssetTypeTree(self, user):
    """
    Build an array representing tree structure of asset types. 
    Each element is a list: label, has add button, list of children lists.
    """
    tree = []
    for top in db.GqlQuery("SELECT * FROM AssetType WHERE parentType = '' ORDER BY sortOrder"):
      item1 = []
      item1.append(top.name)
      item1.append(False) # no add button for 1st level categories, for now anyway
      children1 = []
      item1.append(children1)
      for second in db.GqlQuery("SELECT * FROM AssetType WHERE parentType = '" + 
                                top.name + "' ORDER BY sortOrder"):
        item2 = []
        item2.append(second.name)
        children2 = []
        # Pick and count actual instances
        count = 0
        for inst in db.GqlQuery("SELECT * FROM AssetInstance WHERE assetType = :1 AND user = :2",
                                second.name, user):
          children2.append(inst.name)
          count += 1          
        item2.append(second.maxCount < 0 or count < second.maxCount)
        item2.append(children2)
        children1.append(item2)
      tree.append(item1)
    return tree

  def getDocumentPlaces(self, user):
    list = []
    for doc in db.GqlQuery("SELECT * FROM DocumentPlace WHERE user = :1", user):
      list.append(doc.documentType)
    return list

class AddPage(webapp.RequestHandler):
  """Addition of asset of a certain type. Probably should be moved to AJAX """
  
  def get(self):
    user = users.get_current_user()
    if not user:
      self.response.out.write("Not logged in")
      return
    
    template_values = { 'assetType' : self.request.get('assetType') }
    path = os.path.join(os.path.dirname(__file__), 'html', 'addAsset.html')
    self.response.out.write(template.render(path, template_values))
 
  def post(self):
    user = users.get_current_user()
    if not user:
      self.response.out.write("Not logged in")
      return
    type = self.request.get('assetType')
    name = self.request.get('name')
    
    # TODO Check for duplicate names for this user
    
    # Create and post a new instance
    ai = AssetInstance(user=user, name=name, assetType=type)
    ai.put()
    
    # Fire rules. TODO Build a list of all there is
    global ruleBase
    ruleBase.apply(user, [ai])
    
    # Go back to the main page - the new data should show up there
    self.redirect("/", False)

    
application = webapp.WSGIApplication(
                                     [('/', MainPage), ('/addAsset', AddPage)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
